package com.wh.org.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wh.basic.vo.AjaxResult;
import com.wh.common.dao.TaskEmployeeMapper;
import com.wh.org.dao.IEmployeeDao;
import com.wh.org.dto.EmployeeDto;
import com.wh.org.pojo.Employee;
import com.wh.org.service.IEmployeeService;
import com.wh.system.dao.EmployeeRoleDao;
import com.wh.system.pojo.EmployeeRole;
import com.wh.user.dao.LoginInfoDao;
import com.wh.user.pojo.LoginInfo;
import com.wh.user.pojo.modify;
import com.wh.user.pojo.saltandpwd;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.rmi.CORBA.Util;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class IEmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private IEmployeeDao dao;
    @Autowired
    private LoginInfoDao loginInfoDao;
    @Autowired
    private EmployeeRoleDao employeeRoleDao;
    @Autowired
    private TaskEmployeeMapper taskEmployeeMapper;

    @Transactional
    @Override
    public void add(Employee employee) {

        //处理盐值和密码
        String salt = RandomUtil.randomString(32);
        String md5Pwd = SecureUtil.md5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);

        //先添加logininfo
        LoginInfo logininfo = new LoginInfo();
        BeanUtil.copyProperties(employee,logininfo);
        logininfo.setUsername(employee.getAdminName());
        logininfo.setAccount(employee.getAccount());
        logininfo.setType(0);       //管理员
        logininfo.setDisable(true); //启动
        loginInfoDao.insert(logininfo);//获取到自增ID

        //添加employee的数据
        employee.setLogininfoId(logininfo.getId());
        dao.insert(employee);

        //4.添加员工所对应的角色
        if (ObjectUtil.isNotEmpty(employee.getRolesId())) {
            List<Long> roleIds = employee.getRolesId();
            for (Long roleId1 : roleIds) {
                employeeRoleDao.insert(new EmployeeRole().setRoleId(roleId1).setEmployeeId(employee.getId()));
            }
        }

    }

    @Transactional
    @Override
    public void del(Long id) {
        //先查询登陆信息id
        Employee employee = dao.selectById(id);
        //删除员工对应的角色信息
        QueryWrapper<EmployeeRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.ge("employee_id",id);
        employeeRoleDao.delete(queryWrapper);
        //判断任务表里面是否有员工信息，如果有则删除
        List<EmployeeRole> employeeRoles = taskEmployeeMapper.selectByemployeeId(id);
        if(employeeRoles !=null ) {
           taskEmployeeMapper.deletebyemployeeId(id);
       }
        //删除employee(关联数据先删除从表)
        dao.deleteById(id);
        //删除logininfo(再删除主表)
        loginInfoDao.deleteById(employee.getLogininfoId());
    }

    @Transactional
    @Override
    public void upd(Employee employee) {

        //2.修改登陆信息
        LoginInfo logininfo = loginInfoDao.selectById(employee.getLogininfoId());
        if (employee.getLogininfoId() == null || logininfo == null) {
            logininfo = new LoginInfo();
        }
        //2.1 把员工的数据同步到登录信息中,不同步id
        BeanUtil.copyProperties(employee, logininfo, "id");
        //2.2 设置登录信息的状态
        logininfo.setDisable(employee.getState() == 1);
        //2.3 判断,有登录信息就是修改,没登录信息就是添加
        if (logininfo.getId() != null) {
            loginInfoDao.updateById(logininfo);
        } else {
            //2.4 修改登录信息
            loginInfoDao.insert(logininfo);
            //2.5 把新添加的登录信息关联到员工表中
            employee.setLogininfoId(logininfo.getId());
        }

        //3.更新员工信息
        dao.updateById(employee);

        //4.更新员工角色
        if (ObjectUtil.isNotEmpty(employee.getRolesId())) {
            //4.1 批量删除
            UpdateWrapper<EmployeeRole> uw = new UpdateWrapper<>();
            uw.ge("employee_id", employee.getId());
            employeeRoleDao.delete(uw);

            //4.2 批量添加
            List<Long> roleIds = employee.getRolesId();
            for (Long roleId : roleIds) {
                employeeRoleDao.insert(new EmployeeRole().setRoleId(roleId).setEmployeeId(employee.getId()));
            }
        }

    }


    @Transactional
    @Override
    public void updState(Long id) {
        Employee employee = dao.selectById(id);
        //改变状态: 0->1, 1->0
        employee.setState(Math.abs(employee.getState() - 1));
        dao.updateById(employee);
        //修改Logininfo
        LoginInfo logininfo = new LoginInfo();
        logininfo.setId(employee.getLogininfoId());
        logininfo.setDisable(!logininfo.getDisable());
        loginInfoDao.updateById(logininfo);
    }

    @Override
    public List<Employee> findAll() {
        return dao.selectList(null);
    }

    @Override
    public Employee findById(Long id) {
        return dao.selectById(id);
    }

    @Transactional
    @Override
    public void patchDel(Long[] ids) {


        //1.删除员工对应的角色们和任务数据
        for (Long id : ids) {
            UpdateWrapper<EmployeeRole> uw = new UpdateWrapper<>();
            uw.ge("employee_id", id);
            employeeRoleDao.delete(uw);
            List<EmployeeRole> employeeRoles = taskEmployeeMapper.selectByemployeeId(id);
            if(employeeRoles !=null ) {
                taskEmployeeMapper.deletebyemployeeId(id);
            }
        }
        //2.查询所有员工信息，并获取他们的登录信息
        List<Employee> list = dao.selectBatchIds(Arrays.asList(ids));
        List<Long> logininfoIds = list.stream().map(emp -> emp.getLogininfoId()).collect(Collectors.toList());
        //3.删除所有员工
        dao.deleteBatchIds(Arrays.asList(ids));
        //4.删除员工的登录信息
        loginInfoDao.deleteBatchIds(logininfoIds);
    }

    @Override
    public IPage<Employee> findByPage(EmployeeDto employeeDto) {
        //1.创建查询条件
        QueryWrapper<Employee> qw = new QueryWrapper<>();
        qw.like("admin_name", employeeDto.getKeyword());
        qw.or();
        qw.like("account", employeeDto.getKeyword());
        IPage<Employee> page = new Page<>(employeeDto.getCurrentPage(), employeeDto.getPageSize());
        page.setRecords(dao.findByPage(page, qw));
        page.setTotal(dao.selectCount(qw));
        return page;
    }

    /**
     * 根据店铺id，查询店铺员工
     * @param shopId
     * @return 店铺员工们
     */
    @Override
    public List<Employee> listByShopId(Long shopId) {
        return dao.selectList(new QueryWrapper<Employee>().eq("shop_id",shopId));
    }
    @Transactional
    @Override
    public void modify(modify modify) {
       //获取登录数据表中的id
        Long id = modify.getLoginId();
        //通过id查询所对应的账号id
      Long employeeId=  dao.findIdbyLogininfoId(id);
      //获取前端传递过来的要修改的数据信息
      String username = modify.getAdminName();
      String phone = modify.getPhone();
     //员工表中的数据进行修改
      dao.modify(employeeId,username,phone);
      //登陆表中的数据修改
      dao.updateLogininfo(id,username,phone);
    }

    @Override
    public AjaxResult modifyPassword(modify modify) {
        //先获取传递过来的数据
        String oldPsw = modify.getOldPsw();//输入的密码
        String password = modify.getPassword();//要更新的密码
        Long id = modify.getLoginId();
        Long employeeId = dao.findIdbyLogininfoId(id);
        //查询输入的密码是否正确
        saltandpwd old = dao.selectpwd(employeeId);

        String salt = old.getSalt();//盐值
        String password1 = old.getPassword();//现有密码
        String s = SecureUtil.md5(oldPsw +salt);

        if (!s.equals(password1) ) {
            //输入的密码不一致
            return AjaxResult.me().setSuccess(false).setMessage("输入的旧密码不正确，请重新输入！");
        } else {
            //旧密码一致,更改密码
            String newPwd = SecureUtil.md5(password + salt);//新密码
            //更改员工表的密码
            dao.updatapwd(employeeId, newPwd);
            //将新密码保存到登录表中
            dao.updatePwd(newPwd,id);

            return AjaxResult.me().setSuccess(true).setMessage("密码修改成功，请重新登录");
        }
    }

    @Override
    public boolean isAccountExist(String account) {
        // 根据账号查询数据库，判断是否存在
        Employee employee = dao.findByAccount(account);
        return employee != null;
    }

    @Override
    public boolean isPhoneExist(String phone) {
        // 根据手机号查询数据库，判断是否存在
        Employee employee = dao.findByPhone(phone);
        return employee != null;
    }

}
